package com.itheima.health.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 自定义授权管理
 */
@Component
public class MyUserService implements UserDetailsService {

    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 根据用户名获取用户信息
        User user = userService.getUserByUsername(username);
        // 用户不存在,返回null
        if (user == null) {
            return null;
        }
        // 授权管理列表
        List<GrantedAuthority> list = new ArrayList<>();
        // 获取用户的role信息
        Set<Role> roleSet = user.getRoles();
        // 遍历
        if (roleSet != null && roleSet.size() > 0) {
            for (Role role : roleSet) {
                // 把role放入授权list中
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                // 用户权限一览
                Set<Permission> permissionSet = role.getPermissions();
                if (permissionSet != null && permissionSet.size() > 0) {
                    for (Permission permission : permissionSet) {
                        // 权限放入list中
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }

            }
        }
         String password = user.getPassword();
        // 返回UserDetail对象
        // tring username, String password, Collection<? extends GrantedAuthority> authorities
        return new org.springframework.security.core.userdetails.User(username,password,list);

    }
}
